#include "loadingbutton.h"
#include <QPainter>
#include <QTimer>
LoadingButton::LoadingButton(QWidget *parent)
    : QPushButton(parent)
    , timer(new QTimer(this))
    , angle(0)
    , loading(false)
{
    connect(timer, &QTimer::timeout, this, &LoadingButton::updateAnimation);
}

void LoadingButton::startLoading()
{
    loading = true;
    timer->start(50); //每个50ms启动一次定时器
    setEnabled(false);
}

void LoadingButton::stopLoading()
{
    loading = false;
    timer->stop();
    setEnabled(true);
    update();
}

void LoadingButton::paintEvent(QPaintEvent *event)
{
    QPushButton::paintEvent(event); //先原样绘制

    if (loading) {
        QPainter painter(this);
        //设置绘制抗锯齿
        painter.setRenderHint(QPainter::Antialiasing); //用于设置渲染选项，抗锯齿
        //将桌标原点移到按钮的中心
        painter.translate(width() / 2, height() / 2); //translate() 改变坐标系原点

        painter.rotate(angle); //旋转坐标系
        painter.setPen(Qt::NoPen);
        painter.setBrush(Qt::white);

        QRectF rect(-10, -10, 20, 20); //圆形的大小
        painter.drawPie(rect, 0, 90 * 16);
    }
}

void LoadingButton::updateAnimation()
{
    angle += 10;
    if (angle > 360)
        angle = 0;
    update(); //触发paintEvent事件，但不是立即触发的
}
